import {
  order
} from '../../../../utils/api.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    num: "1", //初始活动人数
    lists: [{
      name: "",
      phone: "",
      personId: ""
    }],
    flag: false,
    memberPrice:0,
    allprice: "",
    preferential: "", //优惠的价格
    pay_price: "", //商品应付的价格
    old_price: "", //商品原价的价格
    canPreferential: "", //成为会员可以优惠的价格
    shppTitle: "",
    shppImg: "",
    isBuyInsurance: false,
    member: "",
    orderParameter: {
      active_id: "",
      num: "",
      attack_id: "",
      member_info: [],
      is_sell_member:1
    },
    name: "",
    phone: "",
    personId: "",
    is_sell_safe: "",
    attack_id:''
  },
  select() {
    this.setData({
      flag: !this.data.flag
    })
    this.totalPrice()
  },
  //减少数量
  delAmount: function(e) {
    var num = this.data.num;
    if (num > 1) {
      this.data.num--;
      this.delList()
    }
    this.setData({
      num: this.data.num
    });
    this.totalPrice()
  },
  //增加数量
  addAmount: function(e) {
    var num = this.data.num;
    if (num < 50) {
      this.data.num++;
      this.addList()
    }
    this.setData({
      num: this.data.num
    });

    this.totalPrice()
  },
  addList: function() {
    var lists = this.data.lists;
    var newData = {
      name: "",
      phone: "",
      personId: ""
    };
    lists.push(newData); //实质是添加lists数组内容，使for循环多一次
    this.setData({
      lists: lists,
    })
  },
  delList: function() {
    var lists = this.data.lists;
    lists.pop(); //实质是删除lists数组内容，使for循环少一次
    this.setData({
      lists: lists,
    })
  },
  totalPrice() {
    let num = this.data.num;
    if (this.data.flag == false) {
      this.setData({
        allprice: this.data.num * this.data.pay_price
      })
    } else {
      this.setData({
        allprice: this.data.num * this.data.pay_price - this.data.canPreferential * this.data.num+36.5
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var memberPrices = wx.getStorageSync('memberPrice')
    var that = this
    let data = JSON.parse(decodeURIComponent(options.data));
    let active_id = 'orderParameter.active_id'
    that.setData({
      preferential: data.preferential, //优惠的价格
      pay_price: data.pay_price, //商品应付的价格
      old_price: data.old_price, //商品应付的价格
      canPreferential: data.canPreferential, //成为会员可以优惠的价格
      shppTitle: data.shppTitle,
      shppImg: data.shppImg,
      allprice: data.pay_price * this.data.num,
      memberPrice: memberPrices,
      member: data.is_member,
      attack_id: data.attack_id,
      [active_id]: data.activityID,
      is_sell_safe: data.is_sell_safe
    })
    if (data.is_sell_safe == true) {
      that.setData({
        isBuyInsurance: true
      })
    } else {
      that.setData({
        isBuyInsurance: false
      })
    }
  },
  nameBlur(e) {
    let lists = this.data.lists
    let index = e.currentTarget.dataset.index
    let namevalue = e.detail.value
    let names = "lists[" + index + "].name"
    this.setData({
      [names]: e.detail.value,
      name: e.detail.value
    })
    let reg = /^[\u4E00-\u9FA5A-Za-z]+$/;
    if (!reg.test(namevalue)) {
      wx.showToast({
        title: '姓名有误',
        duration: 2000,
        icon: 'none'
      });
      return false;
    }
  },
  phoneBlur(e) {
    let lists = this.data.lists
    let phonevalue = e.detail.value
    let index = e.currentTarget.dataset.index
    let phones = "lists[" + index + "].phone"
    this.setData({
      [phones]: e.detail.value,
      phone: e.detail.value
    })
    let reg = /^1[34578]\d{9}$/
    if (!reg.test(phonevalue)) {
      wx.showToast({
        title: '手机号码有误,请检查后再次输入',
        duration: 2000,
        icon: 'none'
      });
      return false;
    }
  },
  idBlur(e) {
    let lists = this.data.lists
    let index = e.currentTarget.dataset.index
    let iDs = "lists[" + index + "].personId"
    let idvalue = e.detail.value
    this.setData({
      [iDs]: e.detail.value,
      personId: e.detail.value
    })
    let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!reg.test(idvalue)) {
      wx.showToast({
        title: '身份证号码有误,请检查后再次输入',
        duration: 2000,
        icon: 'none'
      });
      return false;
    }
  },
  formSubmit(e) {
    let card = e.detail.value.idCard
    let username = e.detail.value.username
    let phone = e.detail.value.phone
    if (phone == "" || username == "" || card == "") {
      wx.showToast({
        title: "请输入相关信息",
        icon: "none"
      })
    }
    if (username != "" && phone != "" && card!=""){
      this.orderPay()
    }
     
  },
  //封装的购买
  orderPay(e) {
    let num = 'orderParameter.num'
    let member_info = 'orderParameter.member_info'
    let attack_id_ = 'orderParameter.attack_id'
    this.setData({
      [num]: this.data.num,
      [attack_id_]: this.data.attack_id,
      [member_info]: this.data.lists
    })
    if (this.data.flag) {
      this.setData({
        ['orderParameter.is_sell_member']: 2,
      })
    }
    if (this.data.is_sell_safe == true) {
      let flagA = true
      for (var i = 0; i < this.data.lists.length; i++) {
        var name = this.data.lists[i].name;
        var personId = this.data.lists[i].personId;
        var phone = this.data.lists[i].phone;
        let reg1 = /^1[34578]\d{9}$/
        let reg2 = /^[\u4E00-\u9FA5A-Za-z]+$/
        let reg3 = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (phone == "" || !reg1.test(phone) || name == "" || !reg2.test(name) || personId == "" || !reg3.test(personId)) {
          flagA = false
        }
      } 
      if (flagA) {
        order(this.data.orderParameter).then(res => {
          if (res.code == 609) {
            wx.showToast({
              title: "下单成功",
              duration: 3000,
              success: function () {
                //立即跳支付
                wx.navigateTo({
                  url: '../../../ordersearch/ordersearch',
                })
              }
            })
          }else if (res.code == 200) {
            let prepay = res.datas
            wx.requestPayment({
              timeStamp: prepay.timestamp,
              nonceStr: prepay.nonceStr,
              package: prepay.package,
              signType: prepay.signType,
              paySign: prepay.paySign,
              success: res => {
                wx.showToast({
                  title: "支付成功",
                  duration: 3000,
                  success: function () {
                    //立即跳支付
                    wx.navigateTo({
                      url: '../../../ordersearch/ordersearch',
                    })
                  }
                })
              },
              fail(res) {
                wx.showToast({
                  title: "支付失败",
                  duration: 3000,
                  success: function () {

                  }
                })
              }
            })
          } else {
            wx.showToast({
              title: "网络故障",
              duration: 3000,
              success: function () {
               
              }
            })
          }
        })
      }
    } else {
      let data = this.data.orderParameter
      delete data.member_info
      order(data).then(res => {
        if (res.code == 609) {
          wx.showToast({
            title: "下单成功",
            duration: 3000,
            success: function () {
              //立即跳支付
              wx.navigateTo({
                url: '../../../ordersearch/ordersearch',
              })
            }
          })
        } else if (res.code == 200) {
          let prepay = res.datas
          wx.requestPayment({
            timeStamp: prepay.timestamp,
            nonceStr: prepay.nonceStr,
            package: prepay.package,
            signType: prepay.signType,
            paySign: prepay.paySign,
            success: res => {
              wx.showToast({
                title: "支付成功",
                duration: 3000,
                success: function () {
                  //立即跳支付
                  wx.navigateTo({
                    url: '../../../ordersearch/ordersearch',
                  })
                }
              })
            },
            fail(res) {
              wx.showToast({
                title: "支付失败",
                duration: 3000,
                success: function () {

                }
              })
            }
          })
        } else {
          wx.showToast({
            title: "网络故障",
            duration: 3000,
            success: function () {

            }
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})